import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { EmojiUsage, EmojiUsageModel } from './../models/emoji-usage.model'

@Injectable()
export class EmojiService {
  constructor(@InjectModel(EmojiUsageModel.name) private emojiUsageModel: Model<EmojiUsage>) {}

  async processMessage(message: string, userId: string, roomId: string): Promise<string> {
    // 匹配中文表情包
    const emojiRegex = /\[([\u4e00-\u9fa5]+)\]/g
    const matches = message.match(emojiRegex)

    if (matches) {
      for (const emoji of matches) {
        // 更新表情包使用记录
        await this.emojiUsageModel.findOneAndUpdate(
          { emoji, roomId },
          {
            $inc: { count: 1 },
            $set: { lastUsed: new Date(), userId },
          },
          { upsert: true, new: true }
        )
      }
    }
    return message
  }

  async getPopularEmojis(roomId: string, limit = 10): Promise<string[]> {
    const popularEmojis = await this.emojiUsageModel
      .find({ roomId })
      .sort({ count: -1 })
      .limit(limit)
      .exec()

    return popularEmojis.map((emoji) => emoji.emoji)
  }
}
